import { defineEventHandler, readBody } from 'h3'
import nodemailer from 'nodemailer'
import config from '../../config'


export default defineEventHandler(async (event) => {
  const { name, email, phone, message } = await readBody(event)

  if (!name || name.trim().length === 0) {
    return { success: false, message: '姓名不能为空' }
  }

  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    return { success: false, message: '请输入有效的邮箱地址' }
  }

  if (!phone || !/^[0-9]{11}$/.test(phone)) {
    return { success: false, message: '请输入有效的11位手机号码' }
  }

  if (!message || message.trim().length === 0) {
    return { success: false, message: '留言内容不能为空' }
  }

  // 配置邮箱服务
  const transporter = nodemailer.createTransport({
    host: 'smtp.163.com', // 你的SMTP服务器
    port: 465,
    secure: true,
    auth: {
      user: '19963981928@163.com',
      pass: 'RMYLWSr4zdDa5VL5'
    }
  })

  // 邮件内容
  const mailOptions = {
    from: '"网站留言" <19963981928@163.com>',
    to: config.mailTo || '1587234887@qq.com', // 接收者
    subject: '新网站留言',
    text: `姓名: ${name}\n邮箱: ${email}\n电话: ${phone}\n留言: ${message}`
  }

  try {
    await transporter.sendMail(mailOptions)
    return { success: true, message: '发送成功' }
  } catch (err) {

    return { success: false, message: '发送失败', error: err }
  }
})